package com.ruoyi.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.alibaba.fastjson2.JSONWriter.Feature.PrettyFormat;

public class MeiYaSms extends BaseSmsSend{

    private static final Logger log = LoggerFactory.getLogger(MeiYaSms.class);

    private static String privateKey = "740a3d3ea1d411ed92bee8611f228a9b";

    private static String urlPrefix = "http://1.85.55.225:8888/expert-sms/proxy/3089/";

    private static String sign = "陕西应急管理";

    private static Boolean openLog = true;
    public SmsSendResponse sendVerificationCode(String mobile, String code) {
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        redisCache.setCacheObject("SmsVerificationCode:" + mobile, code, 5, TimeUnit.MINUTES);
        String content = "您的验证码为：" + code + "，请妥善保管。";
        return send(mobile, content);
    }

    public SmsSendResponse send(String mobiles, String content) {
        Map<String, Object> map = new HashMap(6);
        map.put("private_key", privateKey);
        map.put("op", "send");
        map.put("send_type","direct");
        map.put("content", content);
        map.put("mobiles", mobiles);
        map.put("sign", sign);
        String url = urlPrefix + "/v2/sms/message";
        String body = HttpUtil.post(url, map, 60000);
        if (openLog) {
            log.info("meiya send api, send params, url:{}, map:{}", url, JSONUtil.toJsonStr(map));
            log.info("meiya send api, get body:{}", body);
        }

        if (StrUtil.isBlank(body)) {
            return new SmsSendResponse();
        } else {
            SendResponse sendResponse = JSON.parseObject(body, SendResponse.class);
            SmsSendResponse smsSendResponse = new SmsSendResponse();
            smsSendResponse.setSuccess(sendResponse.isSuccess());
            smsSendResponse.setMsg(sendResponse.getInfo());
            smsSendResponse.setBatchNo(sendResponse.getOrder());
            smsSendResponse.setErrorCode(sendResponse.getInfo());
            return smsSendResponse;
        }
    }


    public List<SmsQueryResponseOrder> query(String orderId) {
        Map<String, Object> map = new HashMap(6);
        map.put("private_key", privateKey);
        map.put("op", "send_detail");
        map.put("order_id",orderId);
        String url = urlPrefix + "v2/sms/message";
        String body = HttpUtil.get(url, map, 60000);
        if (openLog) {
            log.info("meiya send api, send params, url:{}, map:{}", url, JSONUtil.toJsonStr(map));
            log.info("meiya send api, get body:{}", body);
        }

        if (StrUtil.isBlank(body)) {
            return new ArrayList<>();
        } else {
            SmsRecord smsRecord = JSON.parseObject(body, SmsRecord.class);
            smsRecord.setContent("已替换");
            System.out.println("orderId = " + orderId);
            System.out.println(JSON.toJSONString(smsRecord,PrettyFormat));
            if(smsRecord.getOrder() == null || smsRecord.getOrder().size() == 0){
                return new ArrayList<>();
            }
            List<SmsRecordOrder> orders = smsRecord.getOrder();
            List<SmsQueryResponseOrder> responseOrderList = new ArrayList<>();
            for (SmsRecordOrder order : orders) {
                SmsQueryResponseOrder responseOrder = new SmsQueryResponseOrder();
                responseOrder.setMobile(order.getMobile());
                responseOrder.setError(order.isError());
                responseOrder.setSuccess(order.isSuccess());
                responseOrder.setOrderId(orderId);
                responseOrder.setMsg(order.getSend_status());
                responseOrder.setSendTime(order.getSend_time());
                responseOrder.setSubmitTime(order.getSubmit_time());
                responseOrder.setErrorCode(order.getSend_status());
                responseOrderList.add(responseOrder);
            }
            return responseOrderList;
        }
    }

    public static void main(String[] args) {
       new MeiYaSms().query("301752462298090cec98");
        //  new MeiYaSms().send("18966804006", "您的验证码是:1238");
    }

    @Data
    public static class SendResponse {
        private String info;
        private Integer status;
        private Boolean sent;
        private String order;
        // 是否发送成功，这个不是最终状态。最终状态需要通过订单查询接口查询。
        public boolean isSuccess() {
            return StrUtil.equalsIgnoreCase(info, "success");
        }
    }

    @Data
    public static class SmsRecord {
        private String target_count; // 目标发送数量
        private String content;     // 短信内容
        private String status;      // 发送状态
        private int sent_count;      // 已发送数量
        private String create_time;    // 创建时间
        private String sent_time;      // 发送时间
        private List<SmsRecordOrder> order;  // 发送详情列表
        private int waiting_count;   // 等待发送数量
        /**单个发送发送短信成功*/
        public boolean isSingleSuccess() {
            return order!=null && order.size()==1 && "1".equals(order.get(0).getSend_status());
        }
        /**单个发送发送短信失败*/
        public boolean isSingleError() {
            return order!=null && order.size()==1 && ("9".equals(order.get(0).getSend_status()) || "9".equals(status));
        }
        /**单个发送短信等待回执*/
        public boolean isSingleWaiting() {
            return order!=null && order.size()==1 && "2".equals(order.get(0).getSend_status());
        }
        /**单个发送发送短信成功*/
        public boolean isSuccess() {
            return "1".equals(status) || "2".equals(status);
        }
        /**单个发送发送短信失败*/
        public boolean isError() {
            return "9".equals(status);
        }
        /**单个发送短信等待回执*/
        public boolean isWaiting() {
            return "0".equals(status) || "2".equals(status);
        }
    }

    // 内部类 Order
    @Data
    public static class SmsRecordOrder {
        private String send_time;      // 发送时间
        private String submit_time;    // 提交时间
        private String mobile;      // 手机号码
        private String send_status;  // 发送状态

        public boolean isSuccess() {
            return "1".equals(send_status);
        }
        /**单个发送发送短信失败*/
        public boolean isError() {
            return ("9".equals(send_status));
        }
        /**单个发送短信等待回执*/
        public boolean isWaiting() {
            return "2".equals(send_status);
        }
    }

}
